package com.code.zjm.demo.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.code.zjm.demo.entity.Book;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by ZJM on 2017/3/23.
 */

public class MainService extends Service {
    private final String TAG = MainService.class.getSimpleName();//Service类名
    private int count = 0; //计数
    private Timer timer = null;//计时器
    private TimerTask task = null;//计时任务

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind");
        Book book = intent.getParcelableExtra("book");
        Log.i(TAG, "book's information is " + book.getBookName());
        return new ServiceBinder();//使得当前服务与绑定的activity完成绑定
    }

    @Override
    public void onCreate() {
        Log.i(TAG, "onCreate");
        startCount();
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy");
        stopCount();
        super.onDestroy();
    }

    /**
     * 获取当前的数值
     *
     * @return
     */
    public int getCount() {
        return count;
    }

    /**
     * 定义继承 Binder 的内部类
     */
    public class ServiceBinder extends Binder {
        /**
         * 获取当前服务对象
         *
         * @return
         */
        public MainService getService() {
            return MainService.this;
        }
    }

    /**
     * 开启线程计时
     */
    public void startCount() {
        if (timer == null) {
            timer = new Timer();
            task = new TimerTask() {
                @Override
                public void run() {
                    count++;
                    Log.v(TAG, "current count" + count);
                }
            };
            timer.schedule(task, 1000, 1000);
        }
    }

    /**
     * 停止计时
     */
    public void stopCount() {
        if (timer != null) {
            task.cancel();
            timer.cancel();
            //对应启动Timer时的timer是null；
            task = null;
            timer = null;
        }
    }
}
